//
//  SAPrintReceiptStorage.m
//  Saas
//
//  Created by 杨荣 on 2020/6/3.
//  Copyright © 2020 bing. All rights reserved.
//

#import "SAPrintReceiptStorage.h"
#import "SASalesOrderViewListModel.h"
#import "SACommoditySpecialFeesModel.h"
#import "NSString+Print.h"

@interface SAPrintReceiptStorage ()

@property (nonatomic, strong) NSArray *typographyArr;
@property (nonatomic, assign) BOOL isHongKong;

@end

@implementation SAPrintReceiptStorage
+ (void)printWithTotalData:(SACommodityWarehousingSingleModel *)singleModel printSuccessBlock:(SAPrintSuccessBlock)printSuccessBlock {
    static BOOL isFirst = YES;
    
    SAPrintReceiptStorage *this = [[SAPrintReceiptStorage alloc] init];
    this.singleModel = singleModel;
    this.userInfoModel = [SAValueManger shareInStance].userInfo;
    SACommoditySpecialFeesModel *hkSymbol = [SAOverallSetting shareInstance].hkSymbol;
    this.isHongKong = NO;
    if ([hkSymbol.value isEqualToString:@"1"]) {
        this.isHongKong = YES;
    }
    
    SACommoditySpecialFeesModel *ticketLayoutAttribute = [SAOverallSetting shareInstance].ticketLayoutAttribute;
    NSArray *arr = [ticketLayoutAttribute.value componentsSeparatedByString:@","];
    if (arr.count < 18) {
        arr = [NSArray arrayWithObjects:@"0", @"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",nil];
    }
    this.typographyArr = arr;
    
    [this printStoreName];// 打印订单信息
    [this printLineFeed];// 打印换行
    [this printHeader];// 打印头部
    [this printSku];// 打印sku数据
    [this printTotal];// 打印合计值（入库、退货、应付、实付、欠款、余款等）
    [this printBottom];// 打印底部（备足、银行卡信息、电话、地址、提示、操作人、公司名称）
    
    [this printLineFeed];// 打印换行
    [this printLineFeed];// 打印换行
    [this printLineFeed];// 打印换行
    [this printLineFeed];// 打印换行
    [this printPaperCut];// 打印剪纸
    
    [[BluetoothManager sharedInstance] writeToPeripheralWithData:this.writeData success:^{
        NSLog(@"商品入库打印：写入成功");
        if (isFirst) {
            isFirst = NO;
            if (printSuccessBlock) {
                printSuccessBlock();
            }
        }
    } failure:^(NSString * _Nonnull errorMessage) {
        NSLog(@"商品入库打印：写入失败：%@",errorMessage);
        dispatch_async(dispatch_get_main_queue(), ^{
            [Prompt popPromptViewWithMsg:errorMessage duration:2];
        });
    }];
}
// 打印店铺名称
- (void)printStoreName {
    NSString *storeName = self.userInfoModel.storeName;
    NSData *data = [self.escPrinter printCenterText2:storeName font:(PrinterPrintTextFontMiddle)];;
    [self.writeData appendData:data];
}

// 打印头部（单号、日期；厂家、店员）
- (void)printHeader {
    
    NSString *str1 = [NSString stringWithFormat:@"订单: %@",self.singleModel.detailVO.pendOrderNo?self.singleModel.detailVO.pendOrderNo:@""];
    NSString *typeStr = @"入库单";
    NSData *data1 = [self.escPrinter printLeftText:str1 rightText:typeStr font:(PrinterPrintTextFontSmall)];
    [self.writeData appendData:data1];
    
    NSString *dayTime = self.singleModel.detailVO.createDate;
//    if (self.singleModel.detailVO.createDate.length > 11) {
//        dayTime = [self.singleModel.detailVO.createDate substringToIndex:11];
//    }
    NSString *str2 = [NSString stringWithFormat:@"日期: %@",dayTime];
    NSData *data2 = [self.escPrinter printText:str2 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
    [self.writeData appendData:data2];
    
    if ([self.typographyArr[0] isEqualToString:@"0"]) { //0 显示供货商
        NSString *str3 = @"";
        if (self.singleModel.detailVO.providerName.length > 0) {
            str3 = [NSString stringWithFormat:@"供货商: %@",self.singleModel.detailVO.providerName];
            
            NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
            NSString *isSupplier = [NSString stringWithFormat:@"%@",menuList[7][@"isDelete"]];
            NSString *seeProvider = [NSString stringWithFormat:@"%@",menuList[7][@"perms"][@"seeProvider"]];
            if ([isSupplier isEqualToString:@"1"]) {
                str3 = @"供货商: ******";
            }
            if ([seeProvider isEqualToString:@"1"]) {
                str3 = @"供货商: ******";
            }
            
        }else {
            str3 = @"供货商: 零散供货商";
        }
        
        NSData *data3 = [self.escPrinter printText:str3 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
        [self.writeData appendData:data3];
    }
}

// 打印sku数据
- (void)printSku {
    SAOverallSetting *overallSetting = [SAOverallSetting shareInstance];
    NSInteger printerByteWidth = 48;
    if ([overallSetting.printSize.value isEqualToString:@"0"]) {
        printerByteWidth = 42;
    }
    
    SAPrintSkuColorSizeLine *printSku = [[SAPrintSkuColorSizeLine alloc] init];
    if ([overallSetting.printSize.value isEqualToString:@"0"]) {
        NSArray *printSkuStrArray = [printSku warehousingPrintSkuColorSizeLineWithProductSkuArray2:self.singleModel.productInfoList printerByteWidth:printerByteWidth];
        for (NSData *data in printSkuStrArray) {
            [self.writeData appendData:data];
        }
    }else {
        NSArray *printSkuStrArray = [printSku warehousingPrintSkuColorSizeLineWithProductSkuArray:self.singleModel.productInfoList printerByteWidth:printerByteWidth];
        for (NSString *str in printSkuStrArray) {
            NSData *data = [self.escPrinter printText:str font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
            [self.writeData appendData:data];
        }
    }
}

// 打印合计值
- (void)printTotal {
    NSInteger saleCount = 0;
    NSInteger saleStock = 0;
    CGFloat saleTotalPrice = 0.f;
    
    NSInteger returnCount = 0;
    NSInteger returnStock = 0;
    CGFloat returnTotalPrice = 0.f;
    
    for (SASalesOrderViewListModel *model in self.singleModel.productInfoList) {
        NSInteger saleC = 0;
        NSInteger returnC = 0;
        for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
            NSInteger stock = [list.stock integerValue];
            if (stock < 0) {
                returnStock += stock;
                returnTotalPrice += stock * [list.price floatValue] / 100;
                returnC = 1;
            }else {
                saleC = 1;
                saleStock += stock;
                saleTotalPrice += stock * [list.price floatValue] / 100;
            }
        }
        saleCount += saleC;
        returnCount += returnC;
    }
    
    if (saleCount > 0) {
        NSString *str1 = [NSString stringWithFormat:@"入库: %zd款，%zd件，%0.2f元",saleCount,saleStock,saleTotalPrice];
        if (self.isHongKong == YES) {
            str1 = [NSString stringWithFormat:@"入库: %zd款，%zd件，%0.2f港元",saleCount,saleStock,saleTotalPrice];
        }
        [self printWordWrap:str1];
    }
    
    if (returnCount > 0) {
        NSString *str3 = [NSString stringWithFormat:@"退货: %zd款，%zd件，%0.2f元",returnCount,returnStock * -1,returnTotalPrice * -1];
        if (self.isHongKong == YES) {
            str3 = [NSString stringWithFormat:@"退货: %zd款，%zd件，%0.2f港元",returnCount,returnStock * -1,returnTotalPrice * -1];
        }
        if (returnTotalPrice == 0) {
            str3 = [NSString stringWithFormat:@"退货: %zd款，%zd件，0.00元",returnCount,returnStock * -1];
            if (self.isHongKong == YES) {
                str3 = [NSString stringWithFormat:@"退货: %zd款，%zd件，0.00港元",returnCount,returnStock * -1];
            }
        }
        [self printWordWrap:str3];
    }
    
    if ([self.typographyArr[6] isEqualToString:@"6"]) { //6 --’号代表退货
        // 退货标识
        NSString *str2 = [NSString stringWithFormat:@"\"-\"号代表退货"];
        NSData *data2 = [self.escPrinter printText:str2 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
        [self.writeData appendData:data2];
    }
    
    [self printLineFeed];// 打印换行
    
    NSString *str5 = [NSString stringWithFormat:@"应付:%0.2f元",[self.singleModel.detailVO.shouldPrice floatValue]/100.f];
    if (self.isHongKong == YES) {
        str5 = [NSString stringWithFormat:@"应付:%0.2f港元",[self.singleModel.detailVO.shouldPrice floatValue]/100.f];
    }
    NSData *data5 = [self.escPrinter printText:str5 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
    [self.writeData appendData:data5];
    
    NSString *str6 = [NSString stringWithFormat:@"实付:%0.2f元",[self.singleModel.detailVO.shouldPrice floatValue]/100.f];
    if (self.isHongKong == YES) {
        str6 = [NSString stringWithFormat:@"实付:%0.2f港元",[self.singleModel.detailVO.shouldPrice floatValue]/100.f];
    }
    NSData *data6 = [self.escPrinter printText:str6 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
    [self.writeData appendData:data6];
    
    if ([self.typographyArr[7] isEqualToString:@"7"]) { //7 支付方式
        NSString *str8 = [self getDisplayPayWay:(id)self.singleModel.detailPayVOS];// 支付方式
        [self printWordWrap:str8];
    }
    
    SAOverallSetting *overallSetting = [SAOverallSetting shareInstance];
    NSInteger printerByteWidth = 48;
    if ([overallSetting.printSize.value isEqualToString:@"0"]) {
        printerByteWidth = 32;
    }

    NSString *print = kPrint;
    if (print != nil && print.length > 7) {
        NSString *printName = [kPrint substringToIndex:7];
        // 二维码模块大小 1~16
        if ([printName isEqualToString:@"MHT-P58"]) {
            printerByteWidth = 42;
        }
    }
    
    NSString *partingLine = [NSString getPrintPartingLineWithByteWidth:printerByteWidth originX:0];
    NSData *data9 = [self.escPrinter printText:partingLine font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
    [self.writeData appendData:data9];
}


// 打印底部（备注、银行卡信息、电话、地址、提示、操作人、公司名称）
- (void)printBottom {
    
    if (self.singleModel.detailVO.remark.length > 0) {
        NSString *str0 = [NSString stringWithFormat:@"备注: %@",self.singleModel.detailVO.remark];
        NSData *data0 = [self.escPrinter printText:str0 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
        [self.writeData appendData:data0];
    }
    
    if ([self.typographyArr[9] isEqualToString:@"9"]) { //9 操作人
        NSString *str1 = [NSString stringWithFormat:@"操作人: %@",self.singleModel.detailVO.empName];
        NSData *data1 = [self.escPrinter printText:str1 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
        [self.writeData appendData:data1];
    }
    
    if ([self.typographyArr[10] isEqualToString:@"10"]) { //10 联系电话
        if (self.userInfoModel.storeInfo.contactPhone.length > 0) {
            NSString *str2 = [NSString stringWithFormat:@"联系电话: %@",self.userInfoModel.storeInfo.contactPhone];
            NSData *data2 = [self.escPrinter printText:str2 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
            [self.writeData appendData:data2];
        }
    }
    
    if ([self.typographyArr[11] isEqualToString:@"11"]) { //11 联系地址
        if (self.userInfoModel.storeInfo.address.length > 0) {
            NSString *str3 = [NSString stringWithFormat:@"联系地址: %@",self.userInfoModel.storeInfo.address];
            [self printWordWrap:str3];
//            NSData *data3 = [self.escPrinter printText:str3 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
//            [self.writeData appendData:data3];
        }
    }
    
    if ([self.typographyArr[12] isEqualToString:@"12"]) { //12 提醒
        NSString *str4 = @"*钱款、件数请当面点清，离店概不负责";
        if ([SAValueManger shareInStance].userInfo.storeInfo.warnDesc.length > 0) {
            str4 = [SAValueManger shareInStance].userInfo.storeInfo.warnDesc;
        }
        [self printWordWrap:str4];
//        NSData *data4 = [self.escPrinter printText:str4 font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
//        [self.writeData appendData:data4];
    }
    
    // 换行
    [self printLineFeed];
    
    if ([self.typographyArr[13] isEqualToString:@"13"]) { //13 店铺二维码
        NSMutableArray<NSDictionary *> *codeMarr = [NSMutableArray array];
        if ([SAValueManger shareInStance].userInfo.storeInfo.wxQrCode.length > 0) {
            [codeMarr addObject:@{@"店铺二维码":[SAValueManger shareInStance].userInfo.storeInfo.wxQrCode}];
        }
        if (codeMarr.count > 0) {
            NSData *codeData = [self.escPrinter printQRCode:codeMarr];
            [self.writeData appendData:codeData];
        }
    }
    
    if ([self.typographyArr[15] isEqualToString:@"15"]) {
        NSData *data6 = [self.escPrinter printCenterText2:@"深圳市孚云信息科技有限公司" font:(PrinterPrintTextFontSmall)];
        [self.writeData appendData:data6];
        
        NSData *data7 = [self.escPrinter printCenterText2:@"衣点通服装管理系统" font:(PrinterPrintTextFontSmall)];
        [self.writeData appendData:data7];
        NSData *data8 = [self.escPrinter printCenterText2:@"客服热线电话:0755-27804689" font:(PrinterPrintTextFontSmall)];
        [self.writeData appendData:data8];
    }
}

// 打印分割线
- (void)printPartingLine {
    NSData *data = [self.escPrinter printPartingLine:0];
    [self.writeData appendData:data];
}
// 打印换行
- (void)printLineFeed {
    NSData *data = [self.escPrinter lineFeed];
    [self.writeData appendData:data];
}
// 打印剪纸
- (void)printPaperCut {
    NSData *data = [self.escPrinter paperCut];
    [self.writeData appendData:data];
}

-(void)printWordWrap:(NSString *)text {
    SAOverallSetting *overallSetting = [SAOverallSetting shareInstance];
    if ([overallSetting.printSize.value isEqualToString:@"0"]) {
        NSInteger len = [NSString getPrintTextByteTotalWithText:text font:NSStringFontSmall];
        if (len > 32) {
            NSString *newStr = [NSString stringWithFormat:@"%@",text];
            for (int i = 0; i < len; i= i + 32) {
                NSString *str = [newStr getSubStringWithByteWidthMax:32 font:NSStringFontSmall];
                newStr = [newStr substringFromIndex:str.length];
                NSData *data = [self.escPrinter printText:str font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
                [self.writeData appendData:data];
            }
        }else {
            NSData *data = [self.escPrinter printText:text font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
            [self.writeData appendData:data];
        }
    }else {
        NSData *data = [self.escPrinter printText:text font:(PrinterPrintTextFontSmall) alignment:(NSTextAlignmentLeft)];
        [self.writeData appendData:data];
    }
}

@end
